package com.itheima.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.core.domain.AjaxResult;
import com.itheima.common.utils.SecurityUtils;
import com.itheima.server.domain.Activite;
import com.itheima.server.dto.ActiviteDto;
import com.itheima.server.service.ActiviteService;
import com.itheima.server.mapper.ActiviteMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
* @author li
* @description 针对表【hk_activite(促销活动表)】的数据库操作Service实现
* @createDate 2025-09-04 20:39:41
*/
@Service
@Slf4j
public class ActiviteServiceImpl extends ServiceImpl<ActiviteMapper, Activite> implements ActiviteService {
    //活动无效
    private static final int INVALID_STATUS = 1;
    //活动有效
    private static final int Valid = 2;
    /**
     * 编码的长度
     */
    private static final int CODE_LENGTH = 9;
    @Autowired
    private ActiviteMapper activiteMapper;


    /**
     * 添加促销活动
     * @param activiteDto
     * @return
     */
    public Boolean addActivite(ActiviteDto activiteDto) {
        //先判断活动是否存在 活动名称不重复
        Activite one = super.getOne(Wrappers.<Activite>lambdaQuery().eq(Activite::getName, activiteDto.getName()));
        if (!ObjectUtils.isEmpty(one)){
            return false;
        }
        LocalDateTime beginTime = LocalDateTime.parse(activiteDto.getBeginTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        LocalDateTime endTime = LocalDateTime.parse(activiteDto.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        Activite activite = new Activite();
        BeanUtils.copyProperties(activiteDto,activite);
        //随机生成一个六位数编码 要求小写英文字母 不要数字
        activite.setCode(generateRandomLetterCode(CODE_LENGTH));
        activite.setBeginTime(beginTime);
        activite.setEndTime(endTime);
        activite.setCreateBy(SecurityUtils.getUsername());
        activite.setUpdateBy(SecurityUtils.getUsername());

        //判断当前时间是不是在活动时间区间内 不是状态为1 是状态为2
        if (LocalDateTime.now().isBefore(beginTime) || LocalDateTime.now().isAfter(endTime) ){
            activite.setStatus(INVALID_STATUS);
        }
        // else 默认状态为2 有效

        activite.setCreateTime(new Date());
        activite.setUpdateTime(new Date());

        boolean flag = save(activite);
        return flag;
    }

    /**
     * 获取促销活动列表
     * @param pageNum
     * @param pageSize
     * @param beginCreateTime
     * @param endCreateTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public AjaxResult getActiviteList(Integer pageNum, Integer pageSize,String code, String channel,String beginCreateTime, String endCreateTime, String beginTime, String endTime) {
        log.info("查询活动列表: {}",pageNum,pageSize,beginCreateTime,endCreateTime,beginTime,endTime);
        Page<Activite> activityPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Activite> wrapper = new LambdaQueryWrapper<>();
        wrapper.between( beginCreateTime != null && !beginCreateTime.equals("") && endCreateTime != null && !endCreateTime.equals("") ,Activite::getCreateTime,beginCreateTime,endCreateTime)
                .like( beginTime !=null && !beginTime.equals("") ,Activite::getBeginTime,beginTime)
                .like( endTime !=null && !endTime.equals("") ,Activite::getEndTime,endTime)
                .like( code != null && !code.equals(""),Activite::getCode,code)
                .eq( channel != null && !channel.equals(""),Activite::getChannel,channel);
        //分页查询
        Page<Activite> page = super.page(activityPage, wrapper);

        //返回结果
        AjaxResult ajax = new AjaxResult(200, "查询成功");
        ajax.put("total",page.getTotal());
        ajax.put("rows",page.getRecords());
        HashMap<String, Object> params = new HashMap<>();
        params.put("total",page.getTotal());
        params.put("pass",page.getRecords());
        params.put("reject",0);
        params.put("toAudit",0);
        params.put("finish",0);
        ajax.put("params",params);

        return ajax;
    }

    /**
     * 根据活动查询活动信息
     * @param id
     * @return
     */
    public Activite getActiviteById(Long id) {
        log.info("查询活动信息: {}",id);
        Activite activite = super.getById(id);
        return activite;
    }

    /**
     * 修改活动信息
     * @param activite
     * @return
     */
    public Boolean updateActivite(Activite activite) {
        log.info("修改活动信息: {}",activite);
        activite.setUpdateTime(new Date());
        activite.setUpdateBy(SecurityUtils.getUsername());
        //1 是折扣 2是代金券 在添加的时候判断
        Boolean flag = activiteMapper.updateActivite(activite);
        return flag;
    }

    /**
     * 定时更新活动状态
     */
    public void executeActivite() {
        //获取所有活动
        List<Activite> activiteList = super.list();
        if (CollectionUtils.isEmpty(activiteList)){
            return;
        }
        for (Activite activite : activiteList) {
            //先拍判断当前时间是不是在活动时间区间内
            if (LocalDateTime.now().isBefore(activite.getBeginTime()) || LocalDateTime.now().isAfter(activite.getEndTime())){
                //状态为1活动无效
                activite.setStatus(INVALID_STATUS);
            } else {
                // 直接赋值不在判断活动状态 状态为2活动有效
                activite.setStatus(Valid);
            }
        }
    }

    /**
     * 生成指定长度的随机字母字符串
     *
     * @param
     * @return 随机字母字符串
     */
    public String generateRandomLetterCode(int length) {
        // 定义包含所有字母的字符池
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();

        // 生成指定长度的随机字母字符串 生成长度为7
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(letters.length());
            codeBuilder.append(letters.charAt(index));
        }

        return codeBuilder.toString();
    }
}




